# coding=utf-8
from django.forms.models import model_to_dict as django_model_to_dict
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from store_manage.utils import create_success_dict

__all__ = ['paginator']

def paginator(request, q):
    """封装django自带的分页组件"""
    page_num = 1
    page_size = 30

    if request.GET.has_key('page'):
        try:
            page_num = int(request.GET.get('page'))
        except:
            pass

    if request.GET.has_key('limit'):
        try:
            page_size = int(request.GET.get('limit'))
        except:
            pass

    order_field = request.GET.get('order_field', None)
    order_direction = request.GET.get('order_direction', None)

    pag = Paginator(q, page_size)
    try:
        records = pag.page(page_num)
    except PageNotAnInteger:
        records = pag.page(1)
    except EmptyPage:
        records = pag.page(pag.num_pages)

    if order_field:
        order_fields = []
        if isinstance(order_field, (str, unicode)):
            if order_direction == 'desc':
                order_fields.append('-%s' % order_field)
            else:
                order_fields.append(order_field)
        elif isinstance(order_field, list):
            for f in order_field:
                if order_direction == 'desc':
                    order_fields.append('-%s' % f)
                else:
                    order_fields.append(f)

        if order_fields:
            try:
                pag = pag.order_by(*order_fields)
            except Exception,e:
                pass
        try:
            records = records.all()[offset:offset + page_size]
        except Exception,e:
            records = records[offset:offset + page_size]

    ret = create_success_dict(data={
        'page': page_num,
        'page_size': page_size,
        'record_count': pag.count,
        'page_count': pag.num_pages,
        'records': model_list_to_dict(records)
    })
    return ret
